package com.easy.controller;

import com.easy.bean.Attraction;
import com.easy.bean.Itinerary;
import com.easy.service.AttractionService;
import com.easy.service.ItineraryService;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/v1/ai")
@CrossOrigin(origins = "*")
public class ChatController {

    private final ChatClient chatClient;
    private final AttractionService attractionService;
    private final ItineraryService itineraryService;

    @Autowired
    public ChatController(ChatClient chatClient, AttractionService attractionService, ItineraryService itineraryService) {
        this.chatClient = chatClient;
        this.attractionService = attractionService;
        this.itineraryService = itineraryService;
    }

    @GetMapping("/chat")
    public Result generate(HttpServletRequest request,
            @RequestParam(value = "city", defaultValue = "北京") String city,
            @RequestParam(value = "days", defaultValue = "3") Integer days,
            @RequestParam(value = "preferences", defaultValue = "历史,文化") String preferences) {

        try {
            // 从请求头中获取用户token并解析出用户ID
            String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
            Object userIdObj = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
            Integer userId = userIdObj != null ? Integer.valueOf(userIdObj.toString()) : null;

            // 获取符合偏好的景点信息
            List<Attraction> attractions = attractionService.getByCityAndPreferences(city, preferences);

            // 构造提示词给AI模型
            StringBuilder prompt = new StringBuilder();
            prompt.append("请为用户规划一个")
                    .append(days)
                    .append("天的")
                    .append(city)
                    .append("旅行行程，用户的景点偏好是: ")
                    .append(preferences)
                    .append("。\n\n");

            if (attractions == null || attractions.isEmpty()) {
                prompt.append("注意：暂时没有找到符合您偏好的景点信息，请根据")
                        .append(city)
                        .append("的通用信息来规划行程。\n\n");
            } else {
                prompt.append("可用的景点信息如下:\n");

                for (int i = 0; i < Math.min(attractions.size(), 10); i++) {
                    Attraction attraction = attractions.get(i);
                    prompt.append(i + 1)
                            .append(". ")
                            .append(attraction.getName() != null ? attraction.getName() : "未知景点")
                            .append(" - ")
                            .append(attraction.getDescription() != null ? attraction.getDescription() : "暂无描述")
                            .append("\n");
                }
            }

            prompt.append("\n请根据")
                    .append(attractions == null || attractions.isEmpty() ? "城市通用信息" : "这些景点信息")
                    .append("，为用户生成一个详细的")
                    .append(days)
                    .append("天行程安排，要求：\n")
                    .append("1. 每天安排合理的景点数量\n")
                    .append("2. 考虑景点之间的地理位置关系，避免不必要的往返\n")
                    .append("3. 为每个景点提供简短的介绍\n")
                    .append("4. 给出每天的行程建议，包括上午、下午和晚上的安排\n")
                    .append("5. 可以提供一些餐饮和交通建议\n")
                    .append("6. 用中文回复，格式清晰易读\n");

            String aiResponse = chatClient.prompt()
                    .user(prompt.toString())
                    .call()
                    .content();

            // 如果用户已登录，则保存行程到数据库
            // 如果用户已登录，则保存AI生成的行程到数据库
            if (userId != null) {
                // 创建行程主表
                Itinerary itinerary = new Itinerary();
                itinerary.setUser_id(userId);
                itinerary.setCity(city);
                itinerary.setDays(days);
                itinerary.setPreferences(preferences);
                itinerary.setStart_date(LocalDate.now());
                // 保存AI生成的行程内容
                itinerary.setNotes(aiResponse);

                // 添加行程主表记录
                itineraryService.add(itinerary);
            }

            return Result.success(aiResponse);

        } catch (Exception e) {
            System.err.println("行程规划接口异常: " + e.getMessage());
            return Result.fail( 500, "生成行程时发生错误: " + e.getMessage());
        }
    }
}
